﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace StudentSDataBase
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
            else
            {

            }
        }
        private void FillData()
        {
            var strSql = string.Format("select * from Task");
            var sqlDb = Dbhelper.dataTable(strSql);
            Gv_one.DataSource = sqlDb;
            Gv_one.DataBind();
        }
        private string GetVal(int rowIndex , int colIndex)
        {
            var control = Gv_one.Rows[rowIndex].Cells[colIndex];
            var res = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return res;
        }

        //取消编辑
        protected void Gv_one_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Gv_one.EditIndex = -1;
            FillData();
        } 

        //编辑
        protected void Gv_one_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Gv_one.EditIndex = e.NewEditIndex;
            FillData();
        }

        //删除
        protected void Gv_one_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetVal(e.RowIndex, 0);
            var sql = string.Format("delete from Task where id='{0}'",id);
            Dbhelper.OrUpdateOrDelete(sql);
            Gv_one.EditIndex = -1;
            FillData();
        }
        //更新
        protected void Gv_one_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var id = GetVal(e.RowIndex,0);
            var name = GetVal(e.RowIndex,1);
            var content = GetVal(e.RowIndex,2);
            var reamks = GetVal(e.RowIndex,3);
            var sqltext = string.Format("update Task set TaskName='{0}',TaskContent='{1}',Remarks='{2}'where Id='{3}'",name,content,reamks,id);
            
            
            Dbhelper.OrUpdateOrDelete(sqltext);
            Gv_one.EditIndex = -1;


            FillData();
        }

        //详情
        protected void Gv_one_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Response.Redirect("TaskCill.aspx");
        }
        //分页
        protected void Gv_one_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            Gv_one.PageIndex = e.NewPageIndex;
            //Gv_one.EditIndex = -1;
            FillData();
        }

        protected void Gv_one_PageIndexChanging1(object sender, GridViewPageEventArgs e)
        {
            Gv_one.PageIndex = e.NewPageIndex;
            FillData();
        }
    }
}